<%--
  Created by IntelliJ IDEA.
  User: lt
  Date: 2018/5/24
  Time: 20:42
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>

<title>门店 - 调拨要货订单列表</title>

<%--<link rel="stylesheet" href="${contextPath}/static/layer/css/layui.css" media="all">--%>
<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jquery-ui/jquery-ui.css"/>
<%--<link rel="stylesheet" href="${contextPath}/static/statistics/css/bootstrap-datetimepicker.min.css">--%>
<link rel="stylesheet"
      href="${contextPath}/static/ace/components/bootstrap-datepicker/dist/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jqgrid/ui.jqgrid.css"/>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
<%--<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.fr.js"></script>--%>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="${contextPath}/static/statistics/js/vue.js"></script>
<script src="${contextPath}/static/countjs/regularYz.js"></script>

<!-- ztree插件 -->
<link href="${contextPath}/static/ztree/css/zTreeStyle.css" rel="stylesheet" />
<script src="${contextPath}/static/ztree/js/jquery.ztree.core-3.5.js"></script>
<script src="${contextPath}/static/ztree/js/jquery.ztree.excheck-3.5.js"></script>

<%--<jsp:include page="../../head.jsp"/>--%>
<style type="text/css">
    .customBtn {
        line-height: 20px;
        margin-bottom: 3px;
    }

    .btnLine {
        margin-left: 1px;
        margin-top: 8px;
        margin-bottom: 2px;
    }

    @-webkit-keyframes bouncedelay {
        0%, 80%, 100% {
            -webkit-transform: scale(0.0)
        }
        40% {
            -webkit-transform: scale(1.0)
        }
    }

    @keyframes bouncedelay {
        0%, 80%, 100% {
            transform: scale(0.0);
            -webkit-transform: scale(0.0);
        }
        40% {
            transform: scale(1.0);
            -webkit-transform: scale(1.0);
        }
    }

    .autocomplete-suggestions {
        border: 1px solid #999;
        background: #FFF;
        overflow: auto;
    }

    .autocomplete-suggestion {
        padding: 2px 5px;
        white-space: nowrap;
        overflow: hidden;
    }

    .autocomplete-selected {
        background: #F0F0F0;
    }

    .autocomplete-suggestions strong {
        font-weight: normal;
        color: #3399FF;
    }

    @-moz-document url-prefix() {
        fieldset {
            display: table-cell;
        }
    }

    .ui-jqgrid-sortable {
        text-align: center;
    }

    .ui-pg-div{
        display: none;
    }
</style>
<div class="row" id="app">
    <div class="row btnLine">
        <div class="button-len col-sm-12">
            <div style="width: 100%; margin-bottom: 10px;">
                <%--<button class="btn btn-white btn-sm btn-purple customBtn" id="addCargo">--%>
                    <%--<i class="ace-icon fa fa-plus-circle purple"></i> 新增--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="editShop">--%>
                    <%--<i class="ace-icon fa fa-pencil blue"></i> 修改--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="deleteSupplier">--%>
                    <%--<i class="ace-icon fa fa-key red"></i> 删除--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="faqi">--%>
                    <%--<i class="ace-icon fa fa-key red"></i> 发起要货--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="submitOrder">--%>
                    <%--<i class="ace-icon fa fa-key red"></i> 发起订单--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" onclick="shopConfirmDeliverOrder()">--%>
                    <%--<i class="ace-icon fa fa-key red"></i> 到货确认--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                    <%--<i class="ace-icon fa fa-key red"></i> 直调--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" onclick="cancleShopProduct()">--%>
                    <%--<i class="ace-icon fa fa-key red"></i> 退货--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 打印--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 导出--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 设置--%>
                <%--</button>--%>
                <%--<button class="btn btn-white btn-info btn-sm customBtn" id="">--%>
                <%--<i class="ace-icon fa fa-key red"></i> 退出--%>
                <%--</button>--%>
            </div>
            <label style="margin-left: 10px;">选择区域：</label>
            <input id="zoneCode" class="form-control input-sm" type="text" placeholder="区域id" style="display: none">
            <input id="zoneName" onfocus="this.value=''" class="input-sm" type="text" placeholder="区域名称" style="width: 100px;" onclick="zoneHs()" readonly>


            <label style="margin-left: 10px;">选择店铺：</label>
            <input id="shopId" class="form-control input-sm" type="text" placeholder="店铺id" style="display: none">
            <input id="shopName" onfocus="this.value=''" class="input-sm" type="text" placeholder="店铺名称" style="margin-top: -5px; width: 300px;">
            <label>单据状态: </label>
            <select id="state">
                <option value="">==>请选择<==</option>
                <option value="1">==>已处理<==</option>
                <option value="2">==>已提交<==</option>
            </select>
            <%--<input class="input-sm" type="text" id="keyword" style="margin-left: 0px;" value=""--%>
                   <%--placeholder="关键字">--%>
            <button class="btn btn-sm btn-white btn-info search-len customBtn"
                    onclick="searchOrder()">
                <i class="ace-icon fa fa-search orange"></i>搜索
            </button>
        </div>
    </div>
    <!-- 内容数据开始 -->
    <div class="col-xs-12">
        <table id="grid-table"></table>

        <div id="grid-pager"></div>

    </div>
    <!-- 内容数据结束 -->

    <!-- 区域数型内容 -->
    <div id="authorizationInfoContentZone" class="hide">
        <div class="content_wrap">
            <div class="zTreeDemoBackground left">
                <ul id="zoneDemo" class="ztree"></ul>
            </div>
        </div>

        <div>
            <%--<button id="getShopIdBtn" class="btn btn-success btn-sm" style="left: 250px;top: 450px;position: fixed;">确认</button>--%>
        </div>
    </div>
</div>

<input type="text" name="fileStr" id="fileStr" style="display:none"/>
<input type="text" name="fileType" id="fileType" style="display:none"/>

<input type="text" name="fileStr1" id="fileStr1" style="display:none"/>
<input type="text" name="fileType1" id="fileType1" style="display:none"/>

<!-- page specific plugin scripts -->
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.mockjax.js"></script>
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>
<script type="text/javascript">
    var shopIds = '';
    var zoneArray = '';

    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";

    var grid_shop_selector = "#grid-shop-table";
    var pager_shop_selector = "#grid-shop-pager";

    var laypage = layui.laypage,
        layer = layui.layer
    laydate = layui.laydate;

    var queryModel = {
        //分页参数
        page: '1',
        rows: '10',
    }

    var app = new Vue({
        el: '#app',
        data: {
            objcte: [],
            yanType1: [],
            yanType2: [],
            yanType3: [],
            yanType4: [],
            yanType5: [],
        },
        methods: {
//            addProduct: function () {
//                shopInfo();
//                $('#myModal').modal('show');
//            }
        }
    })
    
</script>
<script>
    /**
     * 下啦联动数据绑定 开始代码
     * @type {{parentId: string}}
     */
    $('#isExpInput').change(function () {
        app.yanType2 = []
        app.yanType3 = []
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isExpInput option:selected").val();
        querySubProdType2()
    });

    $('#isAuthInput').change(function () {
        app.yanType3 = []
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isAuthInput option:selected").val();
        querySubProdType3()
    });

    $('#isAuthInput1').change(function () {
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isAuthInput1 option:selected").val();
        querySubProdType4()
    });

    $('#isAuthInput2').change(function () {
        app.yanType5 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = "";
        queryModel.typeId = $("#isAuthInput2 option:selected").val();
        querySubProdType5()
    });

    var querySubProdType1 = function () {
        getSubProdType1(queryModel)
    }
    var querySubProdType2 = function () {
        getSubProdType2(queryModel)
    }
    var querySubProdType3 = function () {
        getSubProdType3(queryModel)
    }
    var querySubProdType4 = function () {
        getSubProdType4(queryModel)
    }
    var querySubProdType5 = function () {
        getSubProdType5(queryModel)
    }


    var getSubProdType1 = function (queryModel) {
         console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
//                 console.log("dataArray: "+dataArray)
                app.yanType1 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType2 = function (queryModel) {
        console.log(queryModel)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
                console.log("dataArray: "+dataArray)
                app.yanType2 = dataArray;

            },
            error: function (error) {
            }
        })
    }

    var getSubProdType3 = function (queryModel) {
        console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
//                console.log("dataArray: "+dataArray)
                app.yanType3 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType4 = function (queryModel) {
        // console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
//                console.log("dataArray: "+dataArray)
                app.yanType4 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType5 = function (queryModel) {
        // console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getProdProperty',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
                $("#commodityScreen").removeClass("hide");
                console.log("dataArray: "+dataArray)
                app.yanType5 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    querySubProdType1(queryModel);

    /**
     * 下啦联动数据绑定 结束代码
     */
</script>

<script type="text/javascript" src="${contextPath}/static/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js"></script>
<script type="text/javascript" src="${contextPath}/static/ace/components/jqGrid/js/jquery.jqGrid.js"></script>
<script type="text/javascript" src="${contextPath}/static/ace/components/jqGrid/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" src="${contextPath}/static/layer/layer.js"></script>
<!-- 调拨订单列表 -->
<script>
    var getShopRequireOrderListByPage = function (shopId) {
        var filters = {
            "rules": [
                {"field": "type","data": '1'},
                {"field": "shopId", "data": shopId}
            ]
        };

        var grid_data = {'filters': JSON.stringify(filters)};

        console.log(grid_data)

        var scripts = [null, "${contextPath}/static/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js", "${contextPath}/static/ace/components/jqGrid/js/jquery.jqGrid.js", "${contextPath}/static/ace/components/jqGrid/js/i18n/grid.locale-cn.js", "${contextPath}/static/layer/layer.js", null]
        $('.page-content-area').ace_ajax('loadScripts', scripts, function () {

            jQuery(function ($) {

                var parent_column = $(grid_selector).closest('[class*="col-"]');
                //resize to fit page size
                $(window).on('resize.jqGrid', function () {
                    $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                })

                //resize on sidebar collapse/expand
                $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
                    if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                        //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
                        setTimeout(function () {
                            $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                        }, 20);
                    }
                })

                jQuery(grid_selector).jqGrid({
                    //direction: "rtl",

                    //subgrid options
                    subGrid: false,
                    url: "${contextPath}/ktPurchase/getShopRequireOrderListByPage",
                    postData: grid_data,
                    datatype: "json",
                    mtype: 'POST',
                    height: 350,

                    colNames: ['订单号','发货方id','发货方','订单总金额','调拨日期', '订单状态'],
                    colModel: [
                        {name: 'id', index: 'id', editable: true, hidden:false, formatter: cLinkId},
                        {name: 'shopId', index: 'shopId', editable: true, hidden:true},
                        {name: 'shopName', index: 'shopName', editable: true},
                        {name: 'amt', index: 'amt', editable: true, hidden: true},
                        {name: 'createTime', index: 'createTime', editable: true},
                        {
                            name: 'state', index: 'state', editable: true,
                            formatter:function(cellvalue, options, rowObject) {
                                var state = rowObject.state;
                                if(state == "2"){
                                    return "已提交";
                                }
                                if (state == "1"){
                                    return "已处理";
                                }
                            }
                        }
                    ],

                    rownumbers: true, //自动行数
//                        width:"1000",
                    autowidth:true,  //宽度自适应
//                        height:"100%",   //高度自适应
                    viewrecords: true,
                    rowNum : 10,//一页显示多少条
                    rowList : [ 10, 20, 30 ],//可供用户选择一页显示多少条
                    pager : pager_selector,//表格页脚的占位符(一般是div)的id
                    sortname : 'gmtModifiedStr',//初始化的时候排序的字段
                    sortorder : "desc",//排序方式,可选desc,asc
//                mtype : "post",//向后台请求数据的ajax的类型。可选post,get
                    altRows: true,
//                toppager: true,
                    multiselect: false,
                    //multikey: "ctrlKey",
                    multiboxonly: false,

                    loadComplete: function () {
                        var table = this;
                        setTimeout(function () {
                            styleCheckbox(table);

                            updateActionIcons(table);
                            updatePagerIcons(table);
                            enableTooltips(table);
                        }, 0);
                    },
                    editurl: "${contextPath}/ktPurchase/getShopRequireOrderListByPage",//nothing is saved
                    caption: "调拨单订单列表",
                    jsonReader: {
                        root: "recordList",
                        page: "currentPage",
                        total: "pageCount",
                        records: "recordCount"
                    },

                    //,autowidth: true,


                    /**
                     ,
                     grouping:true,
                     groupingView : {
				 groupField : ['name'],
				 groupDataSorted : true,
				 plusicon : 'fa fa-chevron-down bigger-110',
				 minusicon : 'fa fa-chevron-up bigger-110'
			},
                     caption: "Grouping"
                     */

                });

                $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

                function cLinkId(cellvalue, options, rowObject){
//                console.log(rowObject)
                    var id = rowObject.id;
                    var shopName = rowObject.shopName;
                    return '<a href="${contextPath}/sys/user/home#page/franchiseeShopAllot-orderinfo&id='+id+'" onclick="">'+id+'</a>';
                }


                /**
                 * 发起订单
                 */
                $("#submitOrder").click(function () {
                    var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
                    if (!id) {
                        layer.msg("提示：请选择一条信息");
                        return;
                    }
                    queryModel.id = id;
                    console.log(queryModel);

                    layer.load(1)
                    $.ajax({
                        url: '${contextPath}/ktPurchase/savePurchaseOrder',
                        type: 'post',
                        data: queryModel,
                        success: function (data) {
                            layer.closeAll('loading');
                            if (data.success == false){
                                layer.msg("获取出错："+data.message)
                                return
                            }
                            var dataArray = data.data;
                            if (dataArray.length == 0){
                                layer.msg("查询没有数据")
                                return
                            }
                            layer.msg("提示："+data.message)
                            console.log(dataArray)
                            editShop(dataArray);
                        },
                        error: function (error) {
                            layer.closeAll('loading')
                        }
                    })
                })


                /**
                 * 修改某条信息
                 */
                $("#editShop").click(function () {
                    var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
                    if (!id) {
                        $.jgrid.info_dialog("提示：", "请选择一条信息");
                        return;
                    }

                    var rowData = $(grid_selector).jqGrid('getRowData', id);
//                console.log(rowData.id);
//                layer.load(1);

                    shopInfo();
//                reload();

                });

                /**
                 * 删除某条数据
                 */
                $("#deleteSupplier").click(function () {
                    var id = $(grid_selector).jqGrid('getGridParam', 'selrow');

                    if (!id) {
                        layer.ms("提示：", "请选择一条信息");
                        return;
                    }
//询问框
                    layer.confirm('将会把这条调拨订单数据删除', {
                        btn: ['确定', '取消'] //按钮
                    }, function () {
                        var rowData = $(grid_selector).jqGrid('getRowData', id);
//                    rowData.id = rowData.id.split('>')[1].split('<')[0];
                        queryModel.id = rowData.id;
                        queryModel.state = rowData.state;
                        layer.load(1);
                        $.ajax({
                            url: '${contextPath}/ktPurchase/saveShopRequireOrder',
                            type: 'post',
                            data: queryModel,
                            dataType: 'json',
                            success: function (data) {
                                layer.closeAll('loading');
                                if (data.success) {
                                    layer.msg('删除成功', {icon: 1});

                                } else {
                                    layer.msg(data.message);
                                }
                                reload();

                            },
                            error: function (error) {
                                layer.closeAll('loading');
                                layer.msg("提示：", "服务器异常，稍后再试");
                            }

                        })

                    }, function () {
                    });
                });

                $("#addCargo").click(function () {
                    shopInfo();
                });

            });
        });
    }

</script>
<!-- 商品列表详情 -->
<script>
    function shopInfo() {
        $('#myModal').modal('show');
        jQuery(grid_shop_selector).jqGrid({
            subGrid: false,
            url : '${contextPath}/ktProd/getProdInfo',
            datatype: "json",
            mtype: 'POST',
            height: 300,
            colNames: ['ID', '商品名称', '供应名称', '类型', '条码','状态','单位','规格', '操作时间','商品来源'],
            colModel: [
                {name: 'productId', index: 'productId', width: 30, editable: true},
                {
                    name: 'productName',
                    index: 'productName',
                    width: 90,
                    editable: true,
                    sortable: false,
                    editrules: {required: true}
                },
//                    {name: 'supplierId', index: 'productId', width: 60, editable: true},
                {
                    name: 'supplierName', index: 'productId', width: 78, editable: true,
                    edittype: 'select'
                },
                {
                    name: 'prodTypeName',
                    index: 'prodTypeName',
                    width: 60,
                    editable: true,
                    sortable: false,
                    editrules: {required: true}
                },
                {
                    name: 'productCode',
                    index: 'productCode',
                    width: 60,
                    editable: true,
                    sortable: false,
                    editrules: {required: true}
                },

                {
                    name: 'state',
                    index: 'state',
                    width: 40,
                    editable: true,
                    sortable: false,
                    edittype: 'select',
                    formatter: function (v, x, r) {
                        return r['state'] == "1" ? "有效" : "无效";
                    },
                    editoptions: {value: "0:有效;1:无效"}
                },
                {
                    name: 'unit',
                    index: 'unit',
                    width: 30,
                    editable: true,
                    sortable: false
                },{
                    name: 'spec',
                    index: 'spec',
                    width: 60,
                    editable: true,
                    sortable: false
                },
                {name: 'stateDate', index: 'stateDate', width: 60, editable: false}

            ],
//                rownumbers: true, //自动行数
            height:"100%",   //高度自适应
//			width: "100%",
            autowidth: true,  //宽度自适应
            viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: pager_shop_selector,
            altRows: true,
            //toppager: true,

            multiselect: true,
            //multikey: "ctrlKey",
            multiboxonly: false,

            loadComplete: function () {
                var table = this;
                setTimeout(function () {
                    styleCheckbox(table);

                    updateActionIcons(table);
                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
            },

            editurl: "${contextPath}/ktProd/getShopListByPage",//nothing is saved
            caption: "店铺列表",
            jsonReader: {
                root: "recordList",
                page: "currentPage",
                total: "pageCount",
                records: "recordCount"
            },
//                onSelectAll: function(rowids,statue){
//                    //函数里做自己的处理
//					queryModel.rowIds = rowids;
//                },
//                resetSelection: function(rowid){
//
//                    return(rowid)
//				}

            //,autowidth: true,


            /**
             ,
             grouping:true,
             groupingView : {
				 groupField : ['name'],
				 groupDataSorted : true,
				 plusicon : 'fa fa-chevron-down bigger-110',
				 minusicon : 'fa fa-chevron-up bigger-110'
			},
             caption: "Grouping"
             */

        });
        //it causes some flicker when reloading or navigating grid
        //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
        //or go back to default browser checkbox styles for the grid
        function styleCheckbox(table) {
            /**
             $(table).find('input:checkbox').addClass('ace')
             .wrap('<label />')
             .after('<span class="lbl align-top" />')


             $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
             .find('input.cbox[type=checkbox]').addClass('ace')
             .wrap('<label />').after('<span class="lbl align-top" />');
             */
        }


        //unlike navButtons icons, action icons in rows seem to be hard-coded
        //you can change them like this in here if you want
        function updateActionIcons(table) {
            /**
             var replacement =
             {
                 'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
                 'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
                 'ui-icon-disk' : 'ace-icon fa fa-check green',
                 'ui-icon-cancel' : 'ace-icon fa fa-times red'
             };
             $(table).find('.ui-pg-div span.ui-icon').each(function(){
				var icon = $(this);
				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
				if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
			})
             */
        }

        //replace icons with FontAwesome icons like above
        function updatePagerIcons(table) {
            var replacement =
                {
                    'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                    'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                    'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                    'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
                };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
        }

        function enableTooltips(table) {
            $('.navtable .ui-pg-button').tooltip({container: 'body'});
            $(table).find('.ui-pg-div').tooltip({container: 'body'});
        }

        //var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

        $(document).one('ajaxloadstart.page', function (e) {
            $.jgrid.gridDestroy(grid_selector);
            $('.ui-jqdialog').remove();
        });

        $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

    }
</script>
<script src=${contextPath}/static/layer/layui.all.js></script>
<script type="text/javascript">

    /**
     * 搜索调拨单
     */
    function searchOrder() {
        var shopId = $("#shopId").val();
        var state = $("#state").val();

        if(shopId == ""){
            shopId = shopIds;
        }

        var filters = {
            "rules": [
                {"field": "shopId", "data": shopId},
                {"field": "state", "data": state}
            ]
        };
        console.log(filters)
        jQuery("#grid-table").jqGrid('setGridParam', {
            postData: {
                "filters": JSON.stringify(filters) //"{'rules' : [{'field' : 'shopName','data' : "+shopName+"},{'field' : 'state','data' : "+state+"}]}"
            }
        }).trigger("reloadGrid");
    }

    /**
     * 搜索商品搜索
     */
    function queryPord() {
        var parentId = queryModel.parentId;
//        var phone = $("#phone").val();
        //var parentDepartmentkey = $("#id_parentDepartmentkey_name").val();

        var filters = {
            "rules": [
                {"field": "parentId", "data": parentId},
                {"field": "parentId", "data": parentId}
            ]
        };
        jQuery(grid_prod_selector).jqGrid('setGridParam', {
            postData: {
                "filters": JSON.stringify(filters) //"{'rules' : [{'field' : 'shopName','data' : "+shopName+"},{'field' : 'state','data' : "+state+"}]}"
            }
        }).trigger("reloadGrid");
    }

    var reload = function () {
//        $(grid_selector).jqGrid('clearGridData');  //清空表格
        $(grid_selector).jqGrid('setGridParam',{
            url:"${contextPath}/ktPurchase/getShopRequireOrderListByPage",
            datatype:'json',
//                    postData:param,
            page: 1,
            rows: 10,
        }).trigger("reloadGrid"); //重新载入
    }

</script>
<script type="application/javascript">
    //it causes some flicker when reloading or navigating grid
    //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
    //or go back to default browser checkbox styles for the grid
    function styleCheckbox(table) {
        /**
         $(table).find('input:checkbox').addClass('ace')
         .wrap('<label />')
         .after('<span class="lbl align-top" />')


         $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
         .find('input.cbox[type=checkbox]').addClass('ace')
         .wrap('<label />').after('<span class="lbl align-top" />');
         */
    }


    //unlike navButtons icons, action icons in rows seem to be hard-coded
    //you can change them like this in here if you want
    function updateActionIcons(table) {
        /**
         var replacement =
         {
             'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
             'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
             'ui-icon-disk' : 'ace-icon fa fa-check green',
             'ui-icon-cancel' : 'ace-icon fa fa-times red'
         };
         $(table).find('.ui-pg-div span.ui-icon').each(function(){
				var icon = $(this);
				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
				if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
			})
         */
    }

    //replace icons with FontAwesome icons like above
    function updatePagerIcons(table) {
        var replacement =
            {
                'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
            };
        $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

            if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
        })
    }

    function enableTooltips(table) {
        $('.navtable .ui-pg-button').tooltip({container: 'body'});
        $(table).find('.ui-pg-div').tooltip({container: 'body'});
    }

</script>
<!-- 业务处理 -->
<script>
    //业务提交
    var submitReq = function () {
        var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
        var ids = $(grid_shop_selector).jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0){
            $("#smallTitle").html("你没有选择添加商品！");
            $("#smallTitle").removeClass("hide");
            return;
        }
        var prodList = [];
        for(var i=0;i<ids.length;i++){
            var idArray = {};
            idArray.id = ids[i];
            prodList.push(idArray);
        }
        prodList.id = idArray;
//        console.log(JSON.stringify(prodList));
        queryModel.prodList = JSON.stringify(prodList);
        queryModel.id = id;
        $.ajax({
            url: '${contextPath}/ktPurchase/saveShopRequireOrder',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示："+data.message)
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    //确定收货
    var shopConfirmDeliverOrder = function () {
        var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
        if(!id){
            layer.msg("提示：请选择一条订单")
            return
        }
//       var rowData = $(grid_selector).jqGrid('getRowData', id);
        queryModel.id = id;
        $.ajax({
            url: '${contextPath}/ktPurchase/shopConfirmDeliverOrder',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示："+data.message)
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    //退货
    var cancleShopProduct = function () {
        var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
        if(!id){
            layer.msg("提示：请选择一条订单")
            return
        }
//        var rowData = $(grid_selector).jqGrid('getRowData', id);
        queryModel.id = id;
        $.ajax({
            url: '${contextPath}/ktPurchase/cancleShopProduct',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示："+data.message)
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    $("#faqi").click(function () {
        var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
        if(!id){
            layer.msg("提示：请选择一条订单")
            return
        }
        var rowData = $(grid_selector).jqGrid('getRowData', id);
        //订单Id
        var orderId = rowData.id;
        queryModel.id = orderId;
        queryModel.state = '1';
        console.log(queryModel)
        $.ajax({
            url: '${contextPath}/ktPurchase/shopRequireOrderCheck',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
                layer.msg("提示："+data.message)
                reload()
            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    });

    var getShop = function () {
        var zoneCode = $("#zoneCode").val();
        queryModel.state = '5';
        queryModel.shopType = "'加盟', '直营'";
        queryModel.zoneCode = zoneCode;
        $.ajax({
            url: '${contextPath}/ktCommon/getShopList2User',
            type: 'post',
            data: queryModel,
            success: function (data) {
                var dataArray = data;
                var shopArray = []
                for(var i = 0; i < dataArray.length; i++){
                    if(shopIds == ''){
                        shopIds = dataArray[i].shopId;
                    }else {
                        shopIds = shopIds + ',' + dataArray[i].shopId;
                    }


                    var shop = {}
                    shop.value = data[i].shopName;
                    shop.data = data[i].shopId;
                    shopArray.push(shop);
                    shopId = data[i].shopId;
                    shopName = data[i].shopName;
                }
                var countries = shopArray
                $('#shopName').autocomplete({
                    lookup: countries,
                    onSelect: function (suggestion) {
//                         alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                        $('#shopId').val(suggestion.data);
                    },
                    minChars: 0,
                });
                //console.log(data)

                getShopRequireOrderListByPage(shopIds);
            },
            error: function (error){
                getShopRequireOrderListByPage(shopIds);
                layer.msg("获取出错："+data.message)
            }
        })
    }

    $('#shopId').change(function () {
        var shopId = $("#shopId").val();
//        var phone = $("#phone").val();
        //var parentDepartmentkey = $("#id_parentDepartmentkey_name").val();

        var filters = {
            "rules": [
                {
                    "field": "shopId",
                    "data": shopId
                }
            ]
        };
        //console.log(filters)
        $(grid_selector).jqGrid('clearGridData');  //清空表格
//        jQuery("#grid-table").jqGrid('setGridParam', {
//            postData: {
//                "filters": JSON.stringify(filters) //"{'rules' : [{'field' : 'shopName','data' : "+shopName+"},{'field' : 'state','data' : "+state+"}]}"
//            }
//        }).trigger("reloadGrid");
    })

    //获取区域
    var getZone = function(){
        layer.load(1);
        var filters = {
            "rules": [
                {"field": "parentId", "data": '0'},
                {"field": "state", "data": '1'},
            ]
        };
        var queryModels = {
            page: '1',
            rows: '10000',
            filters: JSON.stringify(filters),
        };

        $.ajax({
            url : "${contextPath}/ktCommon/getZoneListByPage",
            type : "get",
            data : queryModels,
            dataType : "json",
            async : false,
            success : function(data) {
                layer.closeAll('loading');
                var dataArray = data.recordList;
                zoneArray = dataArray;
            },
            error : function () {
                layer.closeAll('loading');
                layer.msg("网络异常")
            }
        });
    }

    var zoneHs = function () {
        $("#zoneName").val('');
        $("#zoneCode").val('');
        getShop();

        var setting = {
            view: {
                dblClickExpand: false,
                showLine: true,
                selectedMulti: false
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: '0',
                },
                key: {
                    name: 'zoneName'
                }
            },
            <%--async: {--%>
            <%--enable: false, // 设置 zTree是否开启异步加载模式  加载全部信息--%>
            <%--url: "${contextPath}/ktProd/getProdType", // Ajax 获取数据的 URL 地址--%>
            <%--autoParam: ["0"],    // 异步加载时自动提交父节点属性的参数,假设父节点 node = {id:1, name:"test"}，异步加载时，提交参数 zId=1--%>
            <%--//                dataFilter: queryModels,--%>
            <%--},--%>
            callback: { //回调函数
                /**
                 * event:鼠标事件
                 * treeId：树的容器id
                 * treeNode：当前点击的节点
                 */
                //双击
                onDblClick: function (treeId, treeNode) {
                    var treeObj = $.fn.zTree.getZTreeObj("zoneDemo");
                    var node = treeObj.getSelectedNodes();//点击节点后 获取节点数据
                    console.log(node[0].zoneName)
                    $("#zoneName").val(node[0].zoneName);
                    $("#zoneCode").val(node[0].zoneCode);
                    getShop();
                    layer.close(modalIndexZone)
                }
            }
        }
        console.log(zoneArray)

        var zNodes =[];
        $.fn.zTree.init($("#zoneDemo"), setting, zoneArray);
        $("#authorizationInfoContentZone").removeClass("hide")
        modalIndexZone = layer.open({
            type: 1,
            title: '区域',
            closeBtn: 1,
            shadeClose: true,
            maxmin: true,
            area: ['300px','500px'],
            skin: 'yourclass',
            content: $("#authorizationInfoContentZone"),
            end: function () {
                $("#authorizationInfoContentZone").addClass("hide")
            }
        });
    }

    $(function () {
        getZone();
        getShop();
    })


</script>